package com.grandstream.website.app.common;


import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

import org.apache.ibatis.session.RowBounds;



public class BaseServiceCoreImpl extends org.mybatis.spring.support.SqlSessionDaoSupport{
	

	private static final String DEFAULT_LINK_SIGN="_";
	
	private static final String DEFAULT_SELECT="select";
	
	private static final String DEFAULT_PAGE="page";
	
	private static final String DEFAULT_COUNT="count";
	
	private static final String INTERCEPTORSIGN=".";
	
	
	public Page getBasePage(Object obj,Page page,String user_defined_name){
		return getBasePageMethod(obj,page,user_defined_name);
	}
	
	public Page getBasePage(Object obj,Page page){
		return this.getBasePage(obj, page, null);
	}
	
	private Page getBasePageMethod(Object obj,Page page,String user_defined_name){
		if(!Util.judgeObjectNotNull(user_defined_name)){
			String genericsClassName= this.getGenericsClassName(null);
			if(!Util.judgeObjectNotNull(genericsClassName)){
				genericsClassName=obj.getClass().getName();
			}
			user_defined_name=Util.interceptStrEnd(genericsClassName, INTERCEPTORSIGN).trim().toLowerCase();
		}else{
			user_defined_name=user_defined_name.trim();
		}
		
		String selectListAllName=DEFAULT_SELECT+DEFAULT_LINK_SIGN+user_defined_name+DEFAULT_LINK_SIGN+DEFAULT_PAGE; //eg: select_sys_dictionary_page
		int offset =(((page.getPagenum()-1)>0)?(page.getPagenum()-1):0)*page.getPagesize();
		int limit =page.getPagesize();
		java.util.List list =getSqlSession().selectList(selectListAllName.toLowerCase(), obj, new RowBounds(offset, limit));
		int count =(Integer)getSqlSession().selectOne((selectListAllName+DEFAULT_COUNT).toLowerCase(),obj);
		page.setResultList(list);
		page.setResulttotal(count);
		return page;
	}
	
	private String  getGenericsClassName(Class cls){
		if(cls==null){
			cls=this.getClass();
		}
		try {
			Type type =cls.getGenericSuperclass();
			if(type instanceof ParameterizedType){   
				Type[] typeParameters =((ParameterizedType) type).getActualTypeArguments();
				if(typeParameters!=null && typeParameters.length ==1){
					return typeParameters[0].toString();
				}
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return "";
	}

}
